package top.archiesean.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import top.archiesean.handler.RpcClientHandler;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 1. 连接netty服务端
 * 2.提供给调用者主动关闭资源的方法
 * 3. 提供消息发送的方法
 *
 * @author ArchieSean
 * @description rpc客户端
 * @date 2024-03-06
 */
public class RpcClient {

    private String host;
    private int port;
    private EventLoopGroup eventLoopGroup;

    private Channel channel;

    private RpcClientHandler rpcClientHandler = new RpcClientHandler();

    private ExecutorService executorService = Executors.newCachedThreadPool();

    public RpcClient(String host, int port) throws InterruptedException {
        this.host = host;
        this.port = port;
        initConnect();
    }

    /**
     * 连接netty服务端
     */
    public void initConnect() throws InterruptedException {
        try {
            eventLoopGroup = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap()
                    .group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            //客户端业务处理类
                            pipeline.addLast(rpcClientHandler);
                        }
                    });

            channel = bootstrap.connect(host, port).sync().channel();
        } catch (Exception ex) {
            ex.printStackTrace();
            if (channel != null) {
                channel.close();
            }
            if (eventLoopGroup != null) {
                eventLoopGroup.shutdownGracefully();
            }
        }

    }

    /**
     * 用于手动关闭
     */
    public void close() {
        if (channel != null) {
            channel.close();
        }
        if (eventLoopGroup != null) {
            eventLoopGroup.shutdownGracefully();
        }
    }

    /**
     * 发送消息方法
     *
     * @return obj
     */
    public Object send(String msg) throws ExecutionException, InterruptedException {
        rpcClientHandler.setRequestMsg(msg);
        Future submit = executorService.submit(rpcClientHandler);
        return submit.get();
    }

}
